import axios from 'axios'
import qs from 'qs'

const SERVER = 'https://api.huhuiyu.top'

const tokenkey = SERVER + 'tokenkey'

const tokeninfo = {
  load: () => {
    let token = localStorage.getItem(tokenkey)
    return token ? token : ''
  },
  save: data => {
    // 如果应答信息中存在token，则保存到本地储存
    if (data && data.token) {
      localStorage.setItem(tokenkey, data.token)
    }
  },
  clear: () => {
    localStorage.removeItem(tokenkey)
  },
}

const api = {
  uploadUserLogo: (file, callback) => {
    // 上传文件必须使用formdata
    const formdata = new FormData()
    formdata.append('file', file)
    const url = SERVER + '/user/logo'
    const pormise = axios({
      url: url,
      method: 'POST',
      data: formdata,
      headers: {
        // 通过头信息传递token认证信息
        Authorization: tokeninfo.load(),
        // 上传文件的指定类型
        'Content-Type': 'multipart/form-data',
      },
    })
    pormise
      .then(resp => {
        console.log('应答结果', resp.data)
        // 保存token认证信息
        tokeninfo.save(resp.data)
        callback(resp.data)
      })
      .catch(err => {
        console.log('请求出错', err)
        callback({ success: false, message: '出bug,赶紧呼叫老师' })
      })
  },
  userlogo: id => {
    return `${SERVER}/user/logo/${id}?ts=${new Date().getTime()}`
  },
  test: () => {
    console.log('测试信息：', axios, qs)
  },
  send: (url, params, method, callback) => {
    // 请求的方式替换成大写
    method = method ? method.toUpperCase() : 'GET'
    // 完整的url
    url = SERVER + url
    // get请求需要转换参数为查询字符串并拼接到url后面
    if (method == 'GET') {
      url += `?` + qs.stringify(params)
      params = ''
    }
    // 通过axios发起请求
    let pormise = axios({
      url: url,
      method: method,
      data: params,
      headers: {
        // 通过头信息传递token认证信息
        Authorization: tokeninfo.load(),
      },
    })

    pormise
      .then(resp => {
        console.log('应答结果', resp.data)
        // 保存token认证信息
        tokeninfo.save(resp.data)
        callback(resp.data)
      })
      .catch(err => {
        console.log('请求出错', err)
        callback({ success: false, message: '出bug,赶紧呼叫老师' })
      })
  },
  // get请求
  get: (url, params, callback) => {
    api.send(url, params, 'GET', callback)
  },
  // post请求
  post: (url, params, callback) => {
    api.send(url, params, 'POST', callback)
  },
  // delete 请求
  delete: (url, params, callback) => {
    api.send(url, params, 'DELETE', callback)
  },
  // put 请求
  put: (url, params, callback) => {
    api.send(url, params, 'PUT', callback)
  },
  // patch 请求
  patch: (url, params, callback) => {
    api.send(url, params, 'PATCH', callback)
  },
}

export { api as default, api as api }
